package com.moxiao.yfjh.module.blind.common;

import com.aliyun.cloudauth20190307.Client;
import com.aliyun.cloudauth20190307.models.InitFaceVerifyResponse;
import com.aliyun.cloudauth20190307.models.InitFaceVerifyResponseBody;
import com.aliyun.tea.TeaException;
import com.moxiao.yfjh.module.blind.controller.app.controller.user.vo.InitFaceVerifyReqVo;
import com.moxiao.yfjh.module.blind.controller.app.controller.user.vo.MemberUserAuthVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @version 1.0
 * @Author my
 * @Date 2024/3/13 14:29
 **/
@Component
@Slf4j
public class InitFaceVerifyUtils {


    @Value("${aliyun.green.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.green.secret}")
    private String secret;

    private Client client;

    /**
     * 初始化客户端
     *
     * @throws Exception
     */
    @PostConstruct
    public void init() throws Exception {
        log.info("阿里云Api客户的初始化");
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(secret);
        // Endpoint 请参考 https://api.aliyun.com/product/Cloudauth
        config.endpoint = "cloudauth.aliyuncs.com";
        client = new Client(config);
    }

    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public com.aliyun.cloudauth20190307.Client createClient() throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(secret);
        // Endpoint 请参考 https://api.aliyun.com/product/Cloudauth
        config.endpoint = "cloudauth.aliyuncs.com";
        return new com.aliyun.cloudauth20190307.Client(config);
    }


    public Map<String, String> initFaceVerify(InitFaceVerifyReqVo initFaceVerifyReqVo) {

        if (Objects.isNull(initFaceVerifyReqVo)) {
            return null;
        }
//        com.aliyun.cloudauth20190307.Client client = null;
//        try {
//            client = createClient();
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }

        Map<String, String> resultMap = new HashMap<>();
        com.aliyun.cloudauth20190307.models.InitFaceVerifyRequest initFaceVerifyRequest = new com.aliyun.cloudauth20190307.models.InitFaceVerifyRequest();
        initFaceVerifyRequest.setSceneId(1000009437L);
        initFaceVerifyRequest.setOuterOrderNo(UUID.randomUUID().toString());
        initFaceVerifyRequest.setProductCode("ID_PRO");
        initFaceVerifyRequest.setCertType("IDENTITY_CARD");
        initFaceVerifyRequest.setUserId(String.valueOf(initFaceVerifyReqVo.getUserId()));
        initFaceVerifyRequest.setCertName(initFaceVerifyReqVo.getCertName());
        initFaceVerifyRequest.setCertNo(initFaceVerifyReqVo.getCertNo());
        initFaceVerifyRequest.setMetaInfo(initFaceVerifyReqVo.getMetaInfo());
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            InitFaceVerifyResponse initFaceVerifyResponse = client.initFaceVerifyWithOptions(initFaceVerifyRequest, runtime);
            if (Objects.equals(initFaceVerifyResponse.statusCode, 200)) {
                InitFaceVerifyResponseBody body = initFaceVerifyResponse.body;
                if (Objects.equals(body.code, "200")) {
                    InitFaceVerifyResponseBody.InitFaceVerifyResponseBodyResultObject resultObject = body.getResultObject();
                    if (Objects.nonNull(resultObject)) {
                        resultMap.put("code", body.code);
                        resultMap.put("message", body.getMessage());
                        resultMap.put("certifyId", resultObject.certifyId);
                        return resultMap;
                    }
                } else {
                    resultMap.put("code", body.code);
                    resultMap.put("message", body.getMessage());
                    return resultMap;
                }
            }
        } catch (TeaException error) {
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return resultMap;
    }

    /**
     * 根据身份证计算年纪，性别，星座，生肖
     */
    public static int calculateAge(String idNumber) {
        int birthYear = Integer.parseInt(idNumber.substring(6, 10));
        int birthMonth = Integer.parseInt(idNumber.substring(10, 12));
        int birthDay = Integer.parseInt(idNumber.substring(12, 14));

        LocalDate today = LocalDate.now();
        LocalDate birthDate = LocalDate.of(birthYear, birthMonth, birthDay);

        int age = today.getYear() - birthDate.getYear();

        if (today.getMonthValue() < birthDate.getMonthValue() ||
                (today.getMonthValue() == birthDate.getMonthValue() && today.getDayOfMonth() < birthDate.getDayOfMonth())) {
            age--;
        }

        return age;
    }

    public static String determineGender(String idNumber) {
        int genderCode = Integer.parseInt(idNumber.substring(16, 17));
        return genderCode % 2 == 0 ? "2" : "1";
    }

    public static String determineConstellation(String idNumber) {
        int month = Integer.parseInt(idNumber.substring(10, 12));
        int day = Integer.parseInt(idNumber.substring(12, 14));

        if ((month == 1 && day >= 20) || (month == 2 && day <= 18)) {
            return "11";
        } else if ((month == 2 && day >= 19) || (month == 3 && day <= 20)) {
            return "12";
        } else if ((month == 3 && day >= 21) || (month == 4 && day <= 19)) {
            return "1";
        } else if ((month == 4 && day >= 20) || (month == 5 && day <= 20)) {
            return "2";
        } else if ((month == 5 && day >= 21) || (month == 6 && day <= 21)) {
            return "3";
        } else if ((month == 6 && day >= 22) || (month == 7 && day <= 22)) {
            return "4";
        } else if ((month == 7 && day >= 23) || (month == 8 && day <= 22)) {
            return "5";
        } else if ((month == 8 && day >= 23) || (month == 9 && day <= 22)) {
            return "6";
        } else if ((month == 9 && day >= 23) || (month == 10 && day <= 23)) {
            return "7";
        } else if ((month == 10 && day >= 24) || (month == 11 && day <= 22)) {
            return "8";
        } else if ((month == 11 && day >= 23) || (month == 12 && day <= 21)) {
            return "9";
        } else {
            return "10";
        }
    }

    public static String getBirthday(String idNumber) {
        String birthday = idNumber.substring(6, 14);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate date = LocalDate.parse(birthday, formatter);
        return date.toString();
    }

    /**
     * 通过身份证获取性别年龄星座
     *
     * @param idNumber
     * @return
     */
    public MemberUserAuthVO getIdCard(String idNumber) {
        int age = calculateAge(idNumber);
        String gender = determineGender(idNumber);
        String constellation = determineConstellation(idNumber);
        String birthday = getBirthday(idNumber);
        MemberUserAuthVO memberUserAuthVO = new MemberUserAuthVO();
        memberUserAuthVO.setAge(age);
        memberUserAuthVO.setSex(Byte.parseByte(gender));
        memberUserAuthVO.setConstellation(constellation);
        memberUserAuthVO.setBirthday(birthday);
        memberUserAuthVO.setAge(age);
        log.info("年龄：{}岁，性别{}，星座：{}", age, gender, constellation);
        return memberUserAuthVO;
    }
//    public static void main(String[] args) {
//        String idNumber = "370323198109133546";
//        int age = calculateAge(idNumber);
//        String gender = determineGender(idNumber);
//        String constellation = determineConstellation(idNumber);
//        log.info("年龄：{}岁，性别{}，星座：{}",age,gender,constellation);
//    }
//
//

}
